#！encoding:utf-8
from time import time
from soaplib.service import soapmethod
from soaplib.serializers.primitive import String, Integer, Array
from soaplib.wsgi_soap import request
from soaplib.wsgi_soap import SimpleWSGISoapApp
from constants import config_obj,out,err,warn,debug
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from insert_service import InsertMysql
import json





class XinLuoService(SimpleWSGISoapApp):

    @soapmethod(String,String,_returns=String)
    def xl_receiver(self, table_name, xml_data):
        '''
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        '''
        executor.submit(InsertMysql().main_sql,table_name,xml_data)
        return "{status':'success!}"


    def onCall(self, environ):
        request.additional['call_start'] = time()
        # show_china(request.environ)
        # show_china(request.header)
        # show_china(request.additional)
        # show_china(request)
        # show_china(dir(request))

    def onMethodExec(self, environ, body, py_params, soap_params):
        request.additional['method_start'] = time()
        # show_china(request.additional)
        # show_china(['body',body])
        # show_china(['py_params',py_params])
        # show_china(['soap_params',soap_params])


    def onResults(self, environ, py_results, soap_results):
        request.additional['method_end'] = time()
        # show_china(['py_results',py_results])
        # print py_results.text
        # print dir(py_results)


    def onReturn(self, environ, returnString):
        call_start = request.additional['call_start']
        call_end = time()
        method_start = request.additional['method_start']
        method_end = request.additional['method_end']
        # print 'method_start:',method_start
        # print 'method_end:',method_end
        print 'Method took [%s] - total execution time[%s]'% (
            method_end-method_start, call_end-call_start)


if __name__ == '__main__':
    try:
        port = config_obj.webservice.port.value
        executor = ThreadPoolExecutor(3)
        from wsgiref.simple_server import make_server
        server = make_server('localhost', int(port), XinLuoService())
        out("webservice 服务启动,地址:http://localhost:{}?wsdl".format(port))
        server.serve_forever()
    except ImportError:
        print "Error: example server code requires Python >= 2.5"
